/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.processor;

import com.seari.bean.BaseClient;
import com.seari.bean.IPandPortBean;
import io.netty.channel.Channel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class ChannelExchanger implements Runnable
{

    BaseClient client;
    int count;
    Map<String, IPandPortBean> exchangeMap = new HashMap<>();
    String currentServer;
    static final int MAX_RETRY_TIME = 5; //5次判断channel为非活跃状态时，进行重连
    static final int RETRY_INTERVAL = 2; //断连重试间隔，单位：秒
    public static final String MASTER = "MASTER";
    public static final String SLAVE = "SLAVE";
    protected static Logger logger = LoggerFactory.getLogger(ChannelExchanger.class);

    public ChannelExchanger(BaseClient client)
    {
        this.client = client;
    }

    @Override
    public void run()
    {
        while (true)
        {
            Channel channel = client.getChannel();
            boolean flag = false;
            if (null != channel)
            {
                flag = channel.isActive();
            }
            if (!flag) //channel未连接成功
            {
                count++;
                if (count > MAX_RETRY_TIME)
                {
                    try
                    {
                        count = 0; //重置失败计数器
                        exhcangeClient();
                    } catch (Exception ex)
                    {
                        logger.warn(ex.getMessage());
                        continue;
                    }
                }
            } else
            { //channel连接成功，重置失败计数
                count = 0;
            }
            try
            {
                TimeUnit.SECONDS.sleep(RETRY_INTERVAL);
            } catch (InterruptedException ex)
            {
                logger.warn(ex.getMessage());
            }
        }
    }

    public void exhcangeClient()
    {
        String targetServer = "";
        if (currentServer.equals(ChannelExchanger.MASTER))
        {
            targetServer = ChannelExchanger.SLAVE;
        } else
        {
            targetServer = ChannelExchanger.MASTER;
        }
        IPandPortBean iPandPortBean = exchangeMap.get(targetServer);
        client.setHost(iPandPortBean.getIp());
        client.setPort(iPandPortBean.getPort());
        try
        {
            currentServer = targetServer;
            logger.info("exchange server to:{}, ip:{} , port{}", targetServer, iPandPortBean.getIp(), iPandPortBean.getPort());
            client.reset();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public Map<String, IPandPortBean> getExchangeMap()
    {
        return exchangeMap;
    }

    public void setExchangeMap(Map<String, IPandPortBean> exchangeMap)
    {
        this.exchangeMap = exchangeMap;
    }

    public String getCurrentServer()
    {
        return currentServer;
    }

    public void setCurrentServer(String currentServer)
    {
        this.currentServer = currentServer;
    }

}
